package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.FacilityBiz;
import com.useeinfo.oa.modules.base.biz.FacilityGroupBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Facility;
import com.useeinfo.oa.modules.base.entity.FacilityCat;
import com.useeinfo.oa.modules.base.entity.FacilityGroup;
import com.useeinfo.oa.modules.logger.biz.FacilityGroupLogBiz;
import com.useeinfo.oa.modules.logger.entity.FacilityGroupLog;
import com.useeinfo.oa.modules.logger.enums.LogTypeEnum;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: 陈炜
 * @Date: 2018/12/10 09:57
 * @Description: 设备分组action
 */
@Controller
@RequestMapping("/web/admin/facilityGroup")
public class FacilityGroupManageAction {

    @Autowired
    private FacilityGroupBiz facilityGroupBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private FacilityGroupLogBiz facilityGroupLogBiz;

    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/facility/facilityGroupList");
        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "facilityGroupCode", required = false) String facilityGroupCode,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("facilityGroupCode", facilityGroupCode);
        if(StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        return facilityGroupBiz.findJSONList(queryParam);
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id,HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        FacilityGroup facilityGroup = facilityGroupBiz.findModel(StringConverters.ToLong(id));
        modelAndView.addObject("facilityGroup",facilityGroup);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise",enterprise);
        modelAndView.setViewName("pages/admin/facility/facilityGroupEdit");

        return modelAndView;
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeFacilityGroupEdit")
    @ResponseBody
    public ResultDto executeFacilityGroupEdit(FacilityGroup facilityGroup,HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        if (facilityGroupBiz.existFacilityGroupName(facilityGroup,enterprise.getId())) {
            return ResultUtil.error("您输入的分组名称为空或已存在，请重新输入");
        }
        if(facilityGroup.getId()==null){
            facilityGroup.setFacilityGroupCode(facilityGroupBiz.getGroupCode(enterprise.getId()+""));
        }
        facilityGroup.setEnterprise(enterprise);
        facilityGroup.setSystemUserId(systemUser.getId());
        facilityGroup.setSystemUserName(systemUser.getUserName());
        //添加日志
        FacilityGroupLog facilityGroupLog = new FacilityGroupLog();
        if (facilityGroup.getId() == null) {
            facilityGroupLog.setLogTypeEnum(LogTypeEnum.insert);
        } else {
            facilityGroupLog.setLogTypeEnum(LogTypeEnum.update);
        }
        facilityGroupLog.setUserName(systemUser.getUserName());
        facilityGroupLog.setUserId(systemUser.getId());
        facilityGroupBiz.addOrUpdate(facilityGroup);
        facilityGroupLog.setFacilityGroupId(facilityGroup.getId());
        facilityGroupLogBiz.addOrUpdate(facilityGroupLog);
        return ResultUtil.success();
    }


    /**
     * 逻辑删除机构用户信息
     */
    @RequestMapping("/logicRemoveFacilityGroup")
    @ResponseBody
    public ResultDto logicRemoveFacilityGroup(@RequestParam(value = "id", required = false) String idParam,
                                              HttpServletRequest request) {

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("facilityGroupId",idParam);
        List<Facility> facilityList = facilityBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityList)){
            return ResultUtil.error("已关联数据,无法删除!");
        }
        facilityGroupBiz.deleteLogic(facilityGroupBiz.findModel(StringConverters.ToLong(idParam)));
        //添加日志
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        FacilityGroupLog facilityGroupLog = new FacilityGroupLog();
        facilityGroupLog.setLogTypeEnum(LogTypeEnum.delete);
        facilityGroupLog.setUserName(systemUser.getUserName());
        facilityGroupLog.setUserId(systemUser.getId());
        facilityGroupLog.setFacilityGroupId(StringConverters.ToLong(idParam));
        facilityGroupLogBiz.addOrUpdate(facilityGroupLog);
        return ResultUtil.success();
    }

    /**
     * 获取系统模块选择数据
     *
     * @param q
     * @return
     */
    @RequestMapping("/getFacilityGroupSelect")
    @ResponseBody
    public List<SelectVO> getFacilityGroupSelect(@RequestParam(value = "q", required = false) String q,
                                                 @RequestParam(value = "id", required = false) String id,
                                                 HttpServletRequest request) {
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        FacilityGroup facilityGroup = facilityGroupBiz.findModel(StringConverters.ToLong(id));
        if(StringUtils.isBlank(q)&&facilityGroup!=null){
            index = id;
        }
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("searchCode", q);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        List<FacilityGroup> facilityGroupList = facilityGroupBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityGroupList)){
            for(FacilityGroup group : facilityGroupList){
                if(StringUtils.isNotBlank(index)&&index.equals(group.getId()+"")){
                    status = true;
                }
                selectVOS.add(new SelectVO(group.getFacilityGroupName(), group.getId() + ""));
            }
        }
        if(!status&&facilityGroup!=null){
            selectVOS.add(new SelectVO(facilityGroup.getFacilityGroupName(), facilityGroup.getId() + ""));
        }
        return selectVOS;
    }
}
